package com.wl156.activities;

import java.io.IOException;

import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import com.wl156.MyApp;
import com.wl156.R;
import com.wl156.R.xml;
import com.wl156.model.Certificate;
import com.wl156.model.WebServiceClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;

public class Settings extends PreferenceActivity {

	private WebServiceClient mWebServiceClient;
	private Certificate mCertificate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.prefs);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		findPreference("logout").setOnPreferenceClickListener(
				new OnPreferenceClickListener() {
					@Override
					public boolean onPreferenceClick(Preference preference) {
						new LogoutTask(Settings.this).execute();
						return true;
					}
				});
	}
	
	

}

class LogoutTask extends AsyncTask<Void, Void, Object> {
	ProgressDialog mDialog;

	private WebServiceClient mWebServiceClient;
	private Certificate mCertificate;
	private Context mContext;

	public LogoutTask(Context context) {
		mContext = context;
		mWebServiceClient = new WebServiceClient(context);
		mCertificate = ((MyApp) context.getApplicationContext())
				.getCertificateFromXml();
	}

	@Override
	protected void onPreExecute() {
		mDialog = ProgressDialog.show(mContext, "", "注销登录中...");
	};

	@Override
	protected void onPostExecute(Object result) {
//		if (result instanceof SoapPrimitive) {
//			SoapPrimitive isSuccess = (SoapPrimitive) result;
//			if (isSuccess.toString().equals("True")) {
				((MyApp) mContext.getApplicationContext()).logout();
				mContext.startActivity(new Intent(mContext, Login.class));
				((Activity) mContext).finish();
				
				MyApp.sGlobleCertificate = null;
//			} else {
//				Toast.makeText(mContext, "登出失败，请稍候重试", Toast.LENGTH_LONG)
//						.show();
//			}
//		} else {
//			Toast.makeText(mContext, "登出失败，请稍候重试", Toast.LENGTH_LONG).show();
//		}

		mDialog.dismiss();
	};

	@Override
	protected Object doInBackground(Void... params) {
		try {
			return mWebServiceClient.sysLogout(mCertificate);
		} catch (IOException e) {
			return e;
		} catch (XmlPullParserException e) {
			return e;
		}
	}
}